//index.js
var amapFile = require('../../libs/amap-wx');
// var amapFile = require('../../pages/resources/pic/weather_pic/未知.png')
const app = getApp()
// var bmap = require('../../libs/bmap-wx');

var refresh = function (that) {
  wx.showLoading({
    title: '加载中',
  })
  wx.request({
    url: getApp().data.servser + '/parking/list',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': 'Bearer ' + wx.getStorageSync('token')
    },
    success: function (res) {
      for (var i = 0; i < res.data.data.parkingInfos.length; i++) {
        res.data.data.parkingInfos[i].distance = Math.trunc(that.juli(res.data.data.parkingInfos[i].latitude, res.data.data.parkingInfos[i].longitude, app.globalData.latitude, app.globalData.longitude))
      }
      res.data.data.parkingInfos.sort(that.compare('distance'))
      wx.hideLoading()
      that.setData({
        loading: false,
        hideLoading: false,
        parkingInfos: res.data.data.parkingInfos
      })
      wx.setStorageSync('near_id', that.data.parkingInfos[0].seqId)
    }
  })

}
Page({
  data: {
    inputVal: '',
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    need_login: 'yes',
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    username: '',
    password: '',
    istrue: false,
    today: '',
    order_data: '',
    order_time: '',
    end: '',
    trip_id: '',
    // address11: '',
    // humidity11: '',
    // temper11: '',
    // wea11: '',
    // wind11: '',
    // windpower11: '',
    xinxi:{},
    iconpath_weather:'../../pages/resources/pic/weather_pic/未知.png',
    // ak:"tY0RjpdGpwX5rsi9fEFWe1ACZlASI5E6",
  	// weatherData:'',
  	// futureWeather:[]
  },
  getInputUserId: function (e) {
    this.data.username = e.detail.value;
  },
  getInputPwd: function (e) {
    this.data.password = e.detail.value;
  },
  compare: function (property) {
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  },
  confirm: function (e) {
    var that = this;
    wx.request({
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      url: getApp().data.servser + '/trip/order/add',
      data: {
        tripId: that.data.trip_id,
        openId: app.globalData.openid,
        account: wx.getStorageSync('username'),
        payFlag: '0',
        orderDate: that.data.order_data + ' ' + that.data.order_time + ':00'
      },
      success: function (res) {
        if (res.data.code == 500) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '预约成功!',
            icon: 'none',
            duration: 2000
          })
          refresh(that);
          that.setData({
            istrue: false
          })
        }

      }
    })
  },
  onPullDownRefresh: function () {
    var that = this;
    refresh(that)
  },
  yuyue: function (e) {
    console.log(e.currentTarget.dataset.id)
    this.setData({
      trip_id: e.currentTarget.dataset.id,
      istrue: true
    })
  },
  closeDialog: function () {
    this.setData({
      istrue: false
    })
  },
  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "", findResult: [],
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: "", findResult: []
    });
  },
  inputTyping: function (e) {
    let that = this
    this.setData({
      inputVal: e.detail.value
    });
    if (e.detail.value != '') {
      wx.request({
        url: getApp().data.servser + '/parking/list',
        method: 'GET',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        data: {
          name: e.detail.value
        },
        success: function (res) {
          console.log(res.data)
          var data = res.data;
          that.setData({
            findResult: res.data.data.parkingInfos
          });
        }
      });
    } else {
      that.setData({
        findResult: []
      });
    }
  },
  bindGetUserInfo(e) {
    wx.reLaunch({
      url: '../index/index',
    })
  },
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      order_time: e.detail.value
    })
  },
  juli(lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    return s
  },
  onLoad: function () {
    var that = this;
    var myAmapFun=new amapFile.AMapWX({key:'22831d30dcf79bb8b14adfd3639ee703'});
    myAmapFun.getWeather({
      type:'live',
      success(data){
        if(data.city){
          console.log(data);
        
          if(data.weather.data=='雨'||data.weather.data=='阵雨'||data.weather.data=='小雨'||data.weather.data=='中雨'||data.weather.data=='大雨'||data.weather.data=='暴雨'||data.weather.data=='大暴雨'||data.weather.data=='特大暴雨'||data.weather.data=='强阵雨'||data.weather.data=='极端降雨'||data.weather.data=='毛毛雨/细雨'||data.weather.data=='小雨-中雨'||data.weather.data=='中雨-大雨'||data.weather.data=='大雨-暴雨'||data.weather.data=='暴雨-大暴雨'||data.weather.data=='	大暴雨-特大暴雨'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/大雨.png'
            })
          }
          else if(data.weather.data=='晴'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/晴天.png'
            })
          }
          else if(data.weather.data=='霾'||data.weather.data=='中度霾'||data.weather.data=='重度霾'||data.weather.data=='严重霾'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/霾.png'
            })
          }
          else if(data.weather.data=='雷阵雨'||data.weather.data=='强雷阵雨'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/雷阵雨.png'
            })
          }
          else if(data.weather.data=='多云'||data.weather.data=='少云'||data.weather.data=='晴间多云'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/多云.png'
            })
          }
          else if(data.weather.data=='阴'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/阴天.png'
            })
          }
          else if(data.weather.data=='有风'||data.weather.data=='微风'||data.weather.data=='和风'||data.weather.data=='清风'||data.weather.data=='强风/劲风'||data.weather.data=='疾风'||data.weather.data=='大风'||data.weather.data=='烈风'||data.weather.data=='风暴'||data.weather.data=='狂爆风'||data.weather.data=='飓风'||data.weather.data=='热带风暴'||data.weather.data=='龙卷风'){										
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/大风.png'
            })					
          }
          else if(data.weather.data=='雨'||data.weather.data=='阵雨'||data.weather.data=='小雨'||data.weather.data=='中雨'||data.weather.data=='大雨'||data.weather.data=='暴雨'||data.weather.data=='大暴雨'||data.weather.data=='特大暴雨'||data.weather.data=='强阵雨'||data.weather.data=='极端降雨'||data.weather.data=='毛毛雨/细雨'||data.weather.data=='小雨-中雨'||data.weather.data=='中雨-大雨'||data.weather.data=='大雨-暴雨'||data.weather.data=='暴雨-大暴雨'||data.weather.data=='大暴雨-特大暴雨'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/大雨.png'
            })			
          }
          else if(data.weather.data=='雨夹雪'||data.weather.data=='雨雪天气'||data.weather.data=='阵雨夹雪'||data.weather.data=='冻雨'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/雨夹雪.png'
            })						
          }
          else if(data.weather.data=='雪'||data.weather.data=='阵雪'||data.weather.data=='小雪'||data.weather.data=='中雪'||data.weather.data=='大雪'||data.weather.data=='暴雪'||data.weather.data=='小雪-中雪'||data.weather.data=='中雪-大雪'||data.weather.data=='大雪-暴雪'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/大雪.png'
            })
          }
          else if(data.weather.data=='沙尘暴'||data.weather.data=='浮尘'||data.weather.data=='强沙尘暴'||data.weather.data=='扬沙'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/沙尘暴.png'
            })						            	
          }
          else if(data.weather.data=='雾'||data.weather.data=='浓雾'||data.weather.data=='强浓雾'||data.weather.data=='轻雾'||data.weather.data=='特强浓雾'||data.weather.data=='大雾'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/雾.png'
            })						
          }
          else if(data.weather.data=='平静'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/平静.png'
            })
          }
          else if(data.weather.data=='雷阵雨并伴有冰雹'){
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/冰雹.png'
            })
          }
          else{
            that.setData({
              iconpath_weather:'../../pages/resources/pic/weather_pic/未知.png'
            })
          }

          that.setData({
            xinxi:data
            // address11:data.city,
            // humidity11:data.humidity.data,
            // temper11:data.temperature.data,
            // wea11:data.weather.data,
            // wind11:data.winddirection.data,
            // windpower11:data.windpower.data
          });
        }
      }
    })
    // var BMap = new bmap.BMapWX({ 
    //   ak: that.data.ak
    // });
    // var fail = function(data) { 
    //   console.log("失败");
    //   console.log(data);
    // };
    // var success = function(data) { 
    //   console.log("成功");
    //   console.log(data);
      
    //   var weatherData = data.currentWeather[0]; 
    //   var futureWeather = data.originalData.results[0].weather_data;
    //   console.log(futureWeather);
    //   weatherData = '城市：' + weatherData.currentCity + '\n' + 'PM2.5：' + weatherData.pm25 + '\n' +'日期：' + weatherData.date + '\n' + '温度：' + weatherData.temperature + '\n' +'天气：' + weatherData.weatherDesc + '\n' +'风力：' + weatherData.wind + '\n'; 
    //   that.setData({ 
    //     weatherData: weatherData,
    //     futureWeather: futureWeather
    //   }); 
    // };
    // BMap.weather({ 
    //   fail: fail, 
    //   success: success 
    // });

    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        let userInfo = wx.getStorageSync("userInfo")

        if (userInfo.nickName != undefined) {
          console.log(userInfo.nickName != undefined)
          // 记录用户信息
          wx.request({
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            method: "POST",
            url: getApp().data.servser + '/wx/mini/user/add',
            data: {
              openId: getApp().globalData.openid,
              money: 0,
              name: userInfo.nickName
            },
            success: function (res) {

            }
          })
        } else {
          //console.log('没授权')
          wx.navigateTo({
            url: 'login',
          })
        }
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })


    wx.authorize({
      scope: 'scope.userLocation',
      complete: function (res) {
        if (res.errCode == 0) {
          that.setData({
            loadingHidden: true,
            gps: "not open"
          })
        } else {
          that.setData({
            gps: "open"
          })
        }
      },
      success() {
        wx.getLocation({
          type: 'gcj02',
          complete: function (res) {
            if (!res.latitude) {
              that.setData({
                loadingHidden: true,
                gps: "not open"
              })
            } else {
              that.setData({
                gps: "open"
              })
            }
          },
          success: function (res) {
            app.globalData.latitude = res.latitude;
            app.globalData.longitude = res.longitude;
            let latitude = res.latitude;
            let longitude = res.longitude;
            that.setData({
              loading: true
            });
            wx.request({
              url: getApp().data.servser + '/auth',
              method: 'GET',
              data: {
                username: 'admin',
                password: 'iloveyou'
              },
              success: function (res) {
                if (res.data.code == 500) {
                  wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  var token = res.data.token;
                  wx.setStorageSync('token', token);
                  refresh(that)
                }
              }
            });

            wx.request({
              url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=' + getApp().data.tencentMapKey,
              success: res => {
                getApp().data.defaultCity = getApp().data.defaultCity ? getApp().data.defaultCity : res.data.result.ad_info.city;
                getApp().data.defaultCounty = getApp().data.defaultCounty ? getApp().data.defaultCounty : res.data.result.ad_info.district;
                getApp().data.defaultStreet = getApp().data.defaultStreet ? getApp().data.defaultStreet : res.data.result.address;
                that.setData({
                  markers: [{
                    iconPath: "/pages/resources/pic/location-red.png",
                    id: 0,
                    title: that.data.signPoint,
                    latitude: that.data.lat1,
                    longitude: that.data.lng1,
                    width: 25,
                    height: 25
                  }],
                  latitude: latitude, // 当前位置
                  longitude: longitude,
                  location: getApp().data.defaultCity, //省份
                  county: getApp().data.defaultCounty, //城市
                  street: getApp().data.defaultStreet, //街道
                  button_display: 'yes',
                  need_login: 'no',
                  loadingHidden: true
                });

              }
            })
          }



        })
      }

    })

  },

  onGetUserInfo: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // 上传图片
  doUpload: function () {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]

        // 上传图片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

})